# ========================
# T-101 Telegram Bot
#                functions
# ========================


# Отправка сообщения в чат
def msgSend(method, response):

    import json
    import requests
    from core import config

    url   = 'https://api.telegram.org/bot'

    r = requests.post(url + config.tg_token + '/' + method, json = response)
    if not r: raise ValueError('Telegram send error.')


# Запись логов
def setLogs(s):
    import time

    dt=time.strftime('%d.%m.%Y %H:%M:')+'00'

    f=open('log.txt','a')
    f.write(dt + ';' + str(s) + '\n')
    f.close


# WoL (https://gist.github.com/rschuetzler)
class Waker():

    def makeMagicPacket(self, macAddress):
        import socket
        import struct

        # Take the entered MAC address and format it to be sent via socket
        splitMac = str.split(macAddress,':')

        # Pack together the sections of the MAC address as binary hex
        hexMac = struct.pack('BBBBBB', int(splitMac[0], 16),
                             int(splitMac[1], 16),
                             int(splitMac[2], 16),
                             int(splitMac[3], 16),
                             int(splitMac[4], 16),
                             int(splitMac[5], 16))

        self.packet = b'\xff' * 6 + hexMac * 16 #create the magic packet from MAC address

    def sendPacket(self, packet, destIP, destPort = 7):
        import socket
        import struct

        # Create the socket connection and send the packet
        s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(packet,(destIP,destPort))
        s.close()

    def wake(self, macAddress, destIP, destPort=7):
        import socket
        import struct

        self.makeMagicPacket(macAddress)
        self.sendPacket(self.packet, destIP, destPort)
        #print 'Packet successfully sent to', macAddress

